using LDNS.SDK.Commands.Models;
using LDNS.Utilities;

namespace LDNS.Commands
{
    /// <summary>
    /// 设置主域名上游服务器命令处理器
    /// 作者：huobing
    /// </summary>
    public class SetUpstreamMainDomainCommandHandler : CommandHandlerBase<SetUpstreamMainDomainCommand, DefaultCommandResult>
    {
        /// <summary>
        /// 命令名称
        /// </summary>
        public override string CommandName => SetUpstreamMainDomainCommand.NAME;

        /// <summary>
        /// 执行命令
        /// </summary>
        /// <param name="args">命令参数</param>
        /// <returns>命令执行结果</returns>
        public override BaseCommandResult Execute(string[] args)
        {
            try
            {
                var command = new SetUpstreamMainDomainCommand();
                if (!command.Validate(args, out string error))
                {
                    return BaseCommandResult.CreateErrorResult<DefaultCommandResult>(error, SetUpstreamMainDomainCommand.NAME);
                }

                string domain = args[0];
                string upstream = args[1];
                
                // 设置主域名的上游服务器
                bool success = UpstreamDomainManager.Instance.AddDomainMapping(upstream, domain);
                if (!success)
                {
                    return BaseCommandResult.CreateErrorResult<DefaultCommandResult>($"添加域名映射失败: {upstream} -> {domain}", SetUpstreamMainDomainCommand.NAME);
                }
                
                return BaseCommandResult.CreateSuccessResult<DefaultCommandResult>($"已成功设置域名 {domain} 的上游服务器为 {upstream}", SetUpstreamMainDomainCommand.NAME);
            }
            catch (Exception ex)
            {
                return BaseCommandResult.CreateErrorResult<DefaultCommandResult>($"设置上游主域名失败: {ex.Message}", SetUpstreamMainDomainCommand.NAME);
            }
        }
    }
}